#include <stdio.h>
#include <avr\io.h>
#include <avr\interrupt.h>
#define F_CPU 16000000
#include <util/delay.h>

int uart_putchar(char c, FILE *unused);
int uart_getchar(FILE* f);
FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);
FILE mystdin =  FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);


void my_delay()
{
	volatile char k = 0;
	for (int i = 0; i < 255; i++)
	{
		for (int j = 0; j < 255; j++)
		{
			for (int l = 0; l < 50; l++) 
			{
				k++;
			}
		}
	}
}


int get_value()
{
	char  r;
	do {
		r = uart_getchar(NULL);
	} while (r != 'R');

	int distanta = -1;
	{
		char c1 = uart_getchar(NULL) - '0';
		char c2 = uart_getchar(NULL) - '0';
		char c3 = uart_getchar(NULL) - '0';
		distanta = c1*100 + c2*10 + c3;
		uart_getchar(NULL); // read the CR
		if (distanta < 17)
		{
			PORTD = ~0;
		}
		else
			PORTD = 0;
	} 
	return distanta;
}

int main(void)
{
	// Mesajul ce este citit pe seriala si afisat pe LCD
	char message[33];		

	// port d output
	DDRD = 0xFF;
	PORTD = 0;

	// Initializare modul USART pt comunicatie la 9600bps, 8 biti de date, la 16MHz											
	UBRRH = 0;				
	UBRRL = 103;
	UCSRB = 0x18;
	UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0);
	stdin = &mystdin;
	stdout = &mystdout;


	for (;;)
		get_value();

	return 0;
}
int uart_putchar(char c, FILE *unused)      
{
	if (c == '\n')
		uart_putchar('\r', 0);
	loop_until_bit_is_set(UCSRA, UDRE);
	UDR = c;
	return 0;
}

// Functie ce trateaza primirea unui caracter pe seriala
int uart_getchar(FILE* f)
{	
	char c;
    
    loop_until_bit_is_set(UCSRA, RXC);
    c = UDR;
    //if(c=='R')
	//	c='\n';
    //uart_putchar(c,NULL); 
    //flag = ~flag;
	return c;
}

